package org.iteam.xlz.core.service.report;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.iteam.db.BaseService;
import org.iteam.xlz.core.entity.product.ProductSale;
import org.iteam.xlz.core.entity.report.SaleReport;

public class SaleReportService extends BaseService<SaleReport>{
	
	private static SaleReportService instance;
	
	private SaleReportService(){}
	
	public static SaleReportService getInstance(){
		if(null==instance){
			instance=new SaleReportService();
		}
		return instance;
	}
	
	//倒叙排列结果
	public Map<String,List<SaleReport>> query(List<ProductSale> list,Date l,Date r){
		Map<String,List<SaleReport>> map=new TreeMap<String,List<SaleReport>>();
		Calendar last=Calendar.getInstance();//终止时间
		Calendar first=Calendar.getInstance();//起始时间
		Date now=last.getTime();
		if(null==l||null==r){
			first.set(Calendar.DAY_OF_MONTH,1);
		}else{
			first.setTime(l);
			last.setTime(r);
			if(now.getTime()<r.getTime()){
				last.setTime(now);//过滤掉查询"今天以后"时间段的请求
			}
			
			if(now.getTime()<l.getTime()){
				first.setTime(now);//过滤掉查询"今天以后"时间段的请求
			}
		}

		Connection con=null;
		try {
			con=super.getConnection(true);
			while(true){
				if(first.after(last)){
					break;
				}
				
				List<SaleReport> sales=new ArrayList<SaleReport>();
				
				String month=(last.get(Calendar.MONTH)+1)+"";
				String day=last.get(Calendar.DAY_OF_MONTH)+"";
				month=(month.length()==1)?("0"+month):month;
				day=(day.length()==1)?("0"+day):day;
				String type1=last.get(Calendar.YEAR)+"/"+month+"/"+day,
						type2=last.get(Calendar.YEAR)+"-"+month+"-"+day;
				for(ProductSale sale:list){
					StringBuilder sql=new StringBuilder("select '"+type1+"' as time,");
					sql.append("(select count(1) from orderinfo where ppid='"+sale.getPpid()+"' and status=0 and createtime like '%"+type2+"%') as onSale,");
					sql.append("(select count(1) from orderinfo where ppid='"+sale.getPpid()+"' and status=2 and updatetime like '%"+type2+"%') as complete,");
					sql.append("(select count(1) from orderinfo where ppid='"+sale.getPpid()+"' and status=3 and updatetime like '%"+type2+"%') as refund from dual");
					SaleReport sr=super.show(SaleReport.class,con,sql.toString());
					if(null==sr){
						sr=new SaleReport();
					}
					sr.setProductname(sale.getProductname());
					sales.add(sr);
				}
				
				map.put(type1,sales);
				last.add(Calendar.DAY_OF_MONTH,-1);//减一天
			}
			return map;
		} catch (SQLException e) {
			e.printStackTrace();
			return map;
		}finally{
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}